<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 公共方法
 * User: zyw
 * Date: 16/7/26
 * Time: 下午1:48
 */

/**
 * 分页
 * @param $num
 * @param $nowpage
 * @param $pagesize
 * @param $url
 * @return string
 */
function multipage($num, $nowpage, $pagesize, $url){
    $setpages = 10;
    $multipage = '<div class="col-md-9 page_1 col-md-page"><nav><ul class="pagination">';
    $multipage .= '<li class="disabled"><span> 共 : '.$num.' 条记录</span></li>';
    if($num > $pagesize) {
        $page = $setpages + 1;
        $offset = ceil($setpages/2 - 1);
        $pages = ceil($num / $pagesize);

        $from = $nowpage - $offset;
        $to = $nowpage + $offset;
        $more = 0;
        if($page >= $pages) {
            $from = 1;
            $to = $pages;
        } else {
            if($from <= 1) {
                $to = $page-1;
                $from = 1;
            }  elseif($to >= $pages) {
                $from = $pages-($page-2);
                $to = $pages;
            }
            $more = 1;
        }
        if($nowpage > 0) {
            if($nowpage == 1) {
                $multipage .= '<li class="disabled"><a href="javascript:void(0)" aria-label="Previous"><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li class="disabled"><a href="javascript:void(0)">上一页</a></li>';
            } elseif($nowpage > 11 && $more) {
                $multipage .= '<li><a href="'.mpurl($url,1,$pagesize).'"><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li><a href="'.mpurl($url,$nowpage - 1, $pagesize).'" aria-label="Previous">上一页</a></li>';
            } else {
                $multipage .= '<li><a href="'.mpurl($url,1,$pagesize).'"><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li><a href="'.mpurl($url,$nowpage - 1, $pagesize).'" aria-label="Previous">上一页</a></li>';
            }
        }
        for($i = $from; $i <= $to; $i++) {
            if($i != $nowpage) {
                $multipage .= '<li><a href="'.mpurl($url,$i,$pagesize).'">'.$i.'</a></li>';
            } else {
                $multipage .= '<li class="active"><a href="javascript:void(0)">'.$i.'</a></li>';
            }
        }
        if($nowpage < $pages) {
            if($nowpage < $pages-10 && $more) {
                $multipage .= '<li><a href="'.mpurl($url,$nowpage+1,$pagesize).'" aria-label="Next">下一页</a></li>';
                $multipage .= '<li><a href="'.mpurl($url,$pages,$pagesize).'"><span aria-hidden="true">末页</span></a></li>';
            } else {
                $multipage .= '<li><a href="'.mpurl($url,$nowpage+1,$pagesize).'" aria-label="Next">下一页</a></li>';
                $multipage .= '<li><a href="'.mpurl($url,$pages,$pagesize).'"><span aria-hidden="true">末页</span></a></li>';
            }
        } elseif($nowpage == $pages) {
            $multipage .= '<li class="disabled"><a href="javascript:void(0)" aria-label="Next">下一页</a></li>';
            $multipage .= '<li class="disabled"><a href="javascript:void(0)"><span aria-hidden="true">末页</span></a></li>';
        }else{
            $multipage .= '<li><a href="'.mpurl($url,$nowpage+1,$pagesize).'" aria-label="Next">下一页</a></li>';
            $multipage .= '<li><a href="'.mpurl($url,$pages,$pagesize).'"><span aria-hidden="true">末页</span></a></li>';
        }
    }
    return $multipage.'</ul></nav></div>';
}
/**
 * ajax分页
 * @param $num
 * @param $nowpage
 * @param $pagesize
 * @param $url
 * @param $data_id  页面上的数据显示div的id
 * @param $page_id  页面上的分页显示div的id
 * @return string
 */
function ajax_multipage($num, $nowpage, $pagesize, $url, $data_id, $page_id){
    $setpages = 10;
    $multipage = '<div class="col-md-10 page_1 col-md-page"><nav><ul class="pagination">';
    $multipage .= '<li class="disabled"><span> 共 : '.$num.' 条记录</span></li>';
    if($num > $pagesize) {
        $page = $setpages + 1;
        $offset = ceil($setpages/2 - 1);
        $pages = ceil($num / $pagesize);

        $from = $nowpage - $offset;
        $to = $nowpage + $offset;
        $more = 0;
        if($page >= $pages) {
            $from = 1;
            $to = $pages;
        } else {
            if($from <= 1) {
                $to = $page-1;
                $from = 1;
            }  elseif($to >= $pages) {
                $from = $pages-($page-2);
                $to = $pages;
            }
            $more = 1;
        }
        if($nowpage > 0) {
            if($nowpage == 1) {
                $multipage .= '<li class="disabled"><a href="javascript:void(0)" aria-label="Previous"><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li class="disabled"><a href="javascript:void(0)">上一页</a></li>';
            } elseif($nowpage > 11 && $more) {
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,1,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" ><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$nowpage - 1, $pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" aria-label="Previous">上一页</a></li>';
            } else {
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,1,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" ><span aria-hidden="true">首页</span></a></li>';
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$nowpage - 1, $pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" aria-label="Previous">上一页</a></li>';
            }
        }
        for($i = $from; $i <= $to; $i++) {
            if($i != $nowpage) {
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$i,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" >'.$i.'</a></li>';
            } else {
                $multipage .= '<li class="active"><a href="javascript:void(0)">'.$i.'</a></li>';
            }
        }
        if($nowpage < $pages) {
            if($nowpage < $pages-10 && $more) {
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$nowpage+1,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" aria-label="Next">下一页</a></li>';
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$pages,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" ><span aria-hidden="true">末页</span></a></li>';
            } else {
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$nowpage+1,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" aria-label="Next">下一页</a></li>';
                $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$pages,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" ><span aria-hidden="true">末页</span></a></li>';
            }
        } elseif($nowpage == $pages) {
            $multipage .= '<li class="disabled"><a href="javascript:void(0)" aria-label="Next">下一页</a></li>';
            $multipage .= '<li class="disabled"><a href="javascript:void(0)"><span aria-hidden="true">末页</span></a></li>';
        }else{
            $multipage .= '<li><a href="javascript:void(0)" onclick="multipage(\''.mpurl($url,$nowpage+1,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')" aria-label="Next">下一页</a></li>';
            $multipage .= '<li><a href="javascript:void(0)"  onclick="multipage(\''.mpurl($url,$pages,$pagesize).'\',\''.$data_id.'\',\''.$page_id.'\')"><span aria-hidden="true">末页</span></a></li>';
        }
    }
    return $multipage.'</ul></nav></div>';
}
function mpurl($mpurl, $page, $pagesize) {
   return $mpurl.'&page='.$page.'&pagesize='.$pagesize;
}

/**
 * 表单图片上传
 * @param $files FILES
 * @param $file_name 保存的文件名
 * @param $path  上传路径
 * @param int $type 是否压缩图片 (该参数取消)
 * return array
 */
function upload_file($files, $file_name, $path, $type = 1){
    $upload_path = APP_UPLOAD_PATH.$path.date('Ym/d')."/";
    if(!is_dir($upload_path)){
        mkdir($upload_path,0777,true);
    }
    $ret= move_uploaded_file($files['tmp_name'], $upload_path.$file_name);
    if(!empty($ret)){
        list($width, $height, $type, $attr) = getimagesize($upload_path.$file_name);
        if(empty($width) || empty($height)){
            return array();
        }
        $syncFile = new SyncFile();
        $flag = $syncFile->uploadFile($path.date('Ym/d')."/".$file_name, $upload_path.$file_name);
        if($flag){
            $imgArr = array(
                'src'  =>array('w'=>$width,'h'=>$height,'u'=>date('Ym/d')."/".$file_name),
            );
        }else{
            $imgArr = array();
        }
        return $imgArr;
    }
    return array();
}

/**
 * json_code
 * @param $str
 * @return string
 */
function encode_json($str) {
    return urldecode(json_encode(url_encode($str)));
}
function url_encode($str) {
    if(is_array($str)) {
        foreach($str as $key=>$value) {
            $str[urlencode($key)] = url_encode($value);
        }
    } else {
        $str = urlencode($str);
    }
    return $str;
}

/**
 * 标准输出
 * @param $code
 * @param $msg
 * @param $data
 */
function std_out($code=0,$msg='',$data=''){
    header("Content-Type: application/json;charset=utf-8");
    $result = array('errorCode' => $code, 'errorMsg' => $msg, 'responseData' => $data);
    echo json_encode($result,JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 字符串加密、解密函数
 * @param	string	$txt		字符串
 * @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
 * @param	string	$key		密钥：数字、字母、下划线
 * @return	string
 */
function sys_auth($txt, $operation = 'ENCODE', $key = '') {
    if($key=='')
    {
        $key = "otcbtc_coin";
    }
    $txt	= $operation == 'ENCODE' ? (string)$txt : base64_decode($txt);
    $len	= strlen($key);
    $code	= '';
    for($i=0; $i<strlen($txt); $i++){
        $k		= $i % $len;
        $code  .= $txt[$i] ^ $key[$k];
    }
    $code = $operation == 'DECODE' ? $code : base64_encode($code);
    return $code;
}

/**
 * 日志写入
 * @param $action  动作
 * @param $data   数据
 * @param $type  0:普通日志 1:错误日志
 */
function write_action_log($action,$data,$type = 0){
    if(empty($type)){
        file_put_contents(APPPATH.'logs/app_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$action." ".encode_json($data)."\r\n",FILE_APPEND);
    }else{
        file_put_contents(APPPATH.'logs/error_'.date('Ymd').'.log',date("Y-m-d H:i:s")."  ".$action." ".encode_json($data)."\r\n",FILE_APPEND);
    }

}
/**

 * 处理form 提交的参数过滤
 * $string	string  需要处理的字符串或者数组
 * $force	boolean  强制进行处理
 * @return	string 返回处理之后的字符串或者数组
 */
function daddslashes($string, $force = 1) {
    if(is_array($string)) {
        $keys = array_keys($string);
        foreach($keys as $key) {
            $val = $string[$key];
            unset($string[$key]);
            $string[addslashes($key)] = daddslashes($val, $force);
        }
    } else {
        $string = addslashes($string);
    }
    return $string;
}
/**
 * 获取客户端的IP地址
 * @return string
 */
function get_client_ip(){
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
        $ip = getenv("HTTP_CLIENT_IP");
    }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "";
    return($ip);
}

/**
 * 跳转显示信息
 * @param $url
 * @param $status
 * @param $msg
 */
function showMessage($url,$status = 0,$msg = ''){
    if($status){
        header("Location:".$url."&status=".$status."&msg=".$msg);
    }else{
        header("Location:".$url);
    }
    exit;
}
/**
 * 判断手机
 * @param string $mobile
 * @return bool
 */
function is_mobile($mobile = ''){

    if (strlen ( $mobile ) != 11 || ! preg_match ( '/^1[2|3|4|5|8|6|7|8|9][0-9]\d{4,8}$/', $mobile )) {
        return false;
    } else {
        return true;
    }

}
/**
 * 计算两个时间段的时间差
 * @param $begin_time int
 * @param $end_time int
 * @return array
 */
function time_diff($begin_time, $end_time){
    if($begin_time < $end_time) {
        $starttime = $begin_time;
        $endtime = $end_time;

    }else{
        $starttime = $end_time;
        $endtime = $begin_time;
    }

    $timediff = $endtime - $starttime;
    $days     = intval( $timediff / 86400 );
    $remain   = $timediff % 86400;
    $hours    = intval( $remain / 3600 );
    $remain   = $remain % 3600;
    $mins     = intval( $remain / 60 );
    $secs     = $remain % 60;
    $res      = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res;
}

/**
 * 字符截取
 * @param $text
 * @param int $start
 * @param int $limit
 * @return mixed|string
 */
function str_cut($text, $start = 0, $limit = 30) {

    $text = strip_tags($text);
    $text = str_replace(array("\r", "\n","'",'"'), array('', '', '\'', '\"'), $text);
    $text = mb_substr($text, $start, $limit, 'UTF-8');

    return $text;
}

/**
 * 获取当前登陆用户
 * @return array
 */
function getLoginUser(){
    $ci = &get_instance();
    $loginUserKey = $ci->config->config['loginUserKey'];
    $loginData = get_cookie($loginUserKey);
    $userData = json_decode($loginData,true);
    return $userData;
}

/**
 * 二维数组去重
 * @param $array2D
 * @return array
 */
function array_unique_v2($array2D,$key){
    $keys = array();
    $arr = array();
    foreach ($array2D as $v){
        if(!in_array($v[$key], $keys)){
            $arr[] = $v;
        }
        $keys[] = $v[$key];
        $keys = array_unique($keys);
    }
    return $arr;
}

/**
 * 取两个数据不同的数据
 * @param $arr1
 * @param $arr2
 * @param $k
 * @return array
 */
function array_unique_v3($arr1, $arr2, $k){
    $result = array();
    if(empty($arr1) || !is_array($arr1)){
        return $result;
    }
    foreach($arr1 as $a1){
        $state = false;
        foreach($arr2 as $a2){
            if($a1[$k] == $a2[$k]){
                $state = true;
                break;
            }
        }
        if(!$state){
            $result[] = $a1;
        }
    }
    return $result;
}

/**
 * 获取处理后的时间格式
 * @param $dateline
 * @return bool|string
 */
function getToTime($dateline){
    $nowTime = time();

    $n_day = date('Ymd', $nowTime);
    $d_day = date('Ymd', $dateline);
    $c_day = $n_day - $d_day;

    $c_time = time_diff($nowTime, $dateline);
    if($c_time['day'] >= 365){
        return date('Y-m-d H:i', $dateline);
    }else if($c_time['day'] > 1){
        return date('m-d H:i', $dateline);
    }else if($c_time['day'] == 1 || $c_day == 1){
        return '昨天 '.date('H:i', $dateline);
    }else if($c_time['day'] == 0 && $c_time['hour'] >= 1){
        return '今日 '.date('H:i', $dateline);
    }else if($c_time['day'] == 0 && $c_time['hour'] == 0 && $c_time['hour'] > 1){
        return date('i', $dateline)."分钟前";
    }else{
        return '刚刚';
    }
}
/**
 * 判断字符串是否为json
 * @param $str
 * @return bool
 */
function is_json($str){
    $temp = json_decode($str, true);
    return is_array($temp) && json_last_error() == JSON_ERROR_NONE;
}


//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url,$post='',$cookie='', $returnCookie=0){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, 1);
    if($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    if($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if($returnCookie){
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie']  = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info.$data;
    }else{
        return $data;
    }

}

/**
 * 生成token
 * name: onRequest
 * @return string
 * @Author:taiyang
 */
function onRequest()
{
    $tokenKey = 'warn_light_http_auth';
    $nowTime = date("YmdHis",time());
    return md5($tokenKey."#".$nowTime);
}